import { useEffect, useRef, useState } from "react";
import ProForm, {
  ProFormText,
  ProFormSelect,
  ProFormTextArea,
  ProFormTreeSelect,
  ProFormList,
} from "@ant-design/pro-form";
import ProCard from "@ant-design/pro-card";
import { message, Cascader, Col } from "antd";
import { LeftOutlined } from "@ant-design/icons";

import UploadFile from "@/components/UploadFile";
import { add, update, fetchInfo } from "@/api/book";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import { useLocation, history } from "umi";
import MyRate from "@/components/MyRate";
import SpecTables from "@/components/SpecTables";
import { fetchList } from "@/api/bookCategory";
import { fetchList as fetchTemplateList } from "@/api/freeTemplate";

export default () => {
  const location = useLocation();
  const { mallBooksId } = location.query;
  const title = mallBooksId ? "编辑书籍" : "新增书籍";
  const formRef = useRef();
  const [categoryList, setCategoryList] = useState([]);
  const [freeTemplateList, setFreeTemplateList] = useState([]);

  const getCategory = async () => {
    const res = await fetchList({});
    if (res.data) {
      setCategoryList(res.data);
    }
  };

  const getInfo = async () => {
    const res = await fetchInfo({ id: mallBooksId });
    if (res.data) {
      const postData = {
        ...res.data,
      };
      formRef.current.setFieldsValue({
        ...postData,
        categoryIds: postData.categoryIds?.filter(Boolean) || [],
      });
    }
  };

  const getFreeTemplateList = async () => {
    const res = await fetchTemplateList({
      pageNum: 1,
      pageSize: 999999,
    });
    if (res.data) {
      setFreeTemplateList(res.data);
    }
  };

  const defaultData = {
    title: "人生海海",
    author: "麦家",
    publishingHouse: "北京",
    categoryIds: [1402775739686913, 1402806986539008, 1402807027548160],
    freeTemplateId: 1384477391446032,
    picture:
      "https://linkstar.oss-cn-chengdu.aliyuncs.com/admin/banner663cceb6f48c919b0de5f057.jpg",
    specificationRequests: [
      {
        id: 1715261067988,
        specification: "全册",
        costPrice: 100,
        commodityNum: "001",
        price: 100,
        vipPrice: 80,
        weight: 1,
        volume: 1,
      },
      {
        id: 1715261141820,
        specification: "半册",
        costPrice: 50,
        commodityNum: "002",
        price: 50,
        vipPrice: 45,
        weight: 1,
        volume: 1,
      },
    ],
    interest: 5,
    quality: 5,
    guide: 5,
    description: "1",
    introduction: "3",
    harvest: "5",
    ready: "2",
    look: "4",
    read: "6",
  };

  useEffect(() => {
    // formRef.current.setFieldsValue(defaultData);
    getCategory();
    getFreeTemplateList();
    if (mallBooksId) {
      getInfo();
    }
  }, []);

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
      mallBooksId,
    };
    console.log("postData===", postData);
    let func = add;
    if (mallBooksId) {
      func = update;
    }
    const res = await func(postData);
    if (res.code == 200) {
      message.success(title + "成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {title}
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProForm
        layout="horizontal"
        formRef={formRef}
        onFinish={async (values) => {
          return handleAddOrUpdate(values);
        }}
        submitter={{
          render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
        }}
        labelCol={{
          span: 2,
        }}
      >
        <ProCard title="基础信息" bordered>
          <ProFormText
            width="lg"
            label="书名"
            name="title"
            rules={[
              { required: true, message: "请输入书名" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />
          <ProFormText
            width="lg"
            label="作者"
            name="author"
            rules={[
              { required: true, message: "请输入作者" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />
          <ProFormText
            width="lg"
            label="出版社"
            name="publishingHouse"
            rules={[
              { required: true, message: "请输入出版社" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />
          <ProFormTreeSelect
            width="lg"
            name="categoryIds"
            label="分类"
            placeholder="请选择"
            allowClear
            fieldProps={{
              multiple: true,
              options: categoryList?.map((item) => {
                return { ...item, selectable: false };
              }),
              fieldNames: {
                value: "id",
                label: "categoryName",
                children: "children",
              },
            }}
            rules={[{ required: true, message: "请选择分类" }]}
          />

          <ProFormText
            width="lg"
            label="ISBN码"
            name="isbnNum"
            rules={[
              { required: true, message: "请输入ISBN码" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />

          <ProFormSelect
            width="lg"
            name="freeTemplateId"
            label="运费模板"
            allowClear
            fieldProps={{
              options: freeTemplateList,
              fieldNames: {
                label: "tempName",
                value: "id",
              },
            }}
            rules={[{ required: true, message: "请选择运费模板" }]}
          />

          <ProForm.Item
            name="picture"
            label="封面"
            tooltip="建议尺寸：226*268px"
            rules={[{ required: true, message: "请上传图片" }]}
          >
            <UploadFile maxCount={1} />
          </ProForm.Item>

          <ProForm.Item
            name="specificationRequests"
            label="规格"
            rules={[{ required: true, message: "请设置规格" }]}
          >
            <SpecTables storageDisabled={true} />
          </ProForm.Item>
        </ProCard>

        <ProCard style={{ marginTop: 20 }} title="书籍评星" bordered>
          <ProForm.Item
            label="阅读兴趣"
            name="interest"
            rules={[{ required: true, message: "请设置" }]}
          >
            <MyRate />
          </ProForm.Item>
          <ProForm.Item
            label="内容质量"
            name="quality"
            rules={[{ required: true, message: "请设置" }]}
          >
            <MyRate />
          </ProForm.Item>
          <ProForm.Item
            label="心理引导"
            name="guide"
            rules={[{ required: true, message: "请设置" }]}
          >
            <MyRate />
          </ProForm.Item>
        </ProCard>

        <ProCard style={{ marginTop: 20 }} title="详情" bordered>
          <ProFormText label="详情id" name="id" hidden />
          <ProCard title="阅读前">
            <ProFormTextArea
              labelCol={{
                span: 4,
              }}
              fieldProps={{
                rows: 5,
                maxLength: 2000,
                showCount: true,
              }}
              name="description"
              label="前言"
              placeholder="请输入"
            />
            <ProFormTextArea
              labelCol={{
                span: 4,
              }}
              fieldProps={{
                rows: 5,
                maxLength: 2000,
                showCount: true,
              }}
              name="introduction"
              label="作者介绍"
              placeholder="请输入"
            />
            <ProFormTextArea
              labelCol={{
                span: 4,
              }}
              fieldProps={{
                rows: 5,
                maxLength: 2000,
                showCount: true,
              }}
              name="harvest"
              label="得到收获"
              placeholder="请输入"
            />
          </ProCard>

          <ProCard title="阅读中">
            <ProFormTextArea
              labelCol={{
                span: 4,
              }}
              fieldProps={{
                rows: 5,
                maxLength: 2000,
                showCount: true,
              }}
              name="ready"
              label="做好阅读准备"
              placeholder="请输入"
            />

            <ProFormTextArea
              labelCol={{
                span: 4,
              }}
              fieldProps={{
                rows: 5,
                maxLength: 2000,
                showCount: true,
              }}
              name="look"
              label="看一看"
              placeholder="请输入"
            />
            <ProFormTextArea
              labelCol={{
                span: 4,
              }}
              fieldProps={{
                rows: 5,
                maxLength: 2000,
                showCount: true,
              }}
              name="read"
              label="读一读"
              placeholder="请输入"
            />
          </ProCard>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};
